<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>观察者模式</title>
</head>
<body>
    <script>
        //目标（发布者）
        //dependency
        class Dep {
            constructor () {
                //存储所有的观察者
                this.subs = []
            }
            
            //添加观察者
            addSubs(sub){
                if(sub && sub.update){
                    this.subs.push(sub)
                }
            }

            //通知所有观察者
            notify(){
                this.subs.forEach(sub => {
                    sub.update()
                })
            }
        }

        //观察者(订阅者)
        //Watcher
        class Watcher {
            update() {
                console.log('update');
            }
        }

        let dep = new Dep()
        let watcher = new Watcher()
        dep.addSubs(watcher)
        dep.notify()
    </script>
</body>
</html>